import React, { Component } from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Button, message } from 'antd';
import {
  WeaLocaleProvider,
  WeaTableEditable,
  WeaNewScroll,
  WeaSearchGroup,
  WeaHelpfulTip,
  WeaMoreButton,
} from 'ecCom';
import { RenderForm } from '../util';

const getLabel = WeaLocaleProvider.getLabel;

@inject('settingStore')
@observer
class AutoClearRule extends Component {
  static defaultProps = {
    prefixCls: 'email-setting-autoClearRule',
  };

  constructor(props) {
    super(props);

    this.state = {
      clearVisible: false,
    };
    this.MailClearLogDialog =
      (window.weaEmailEngine &&
        window.weaEmailEngine.components &&
        window.weaEmailEngine.components.MailClearLogDialog) ||
      React.Fragment;
  }

  componentDidMount() {
    const {
      settingStore: { autoClearRuleStore, setStoreState },
    } = this.props;
    let rightMenuDatas = [
      {
        key: 'save',
        icon: <i className="icon-coms-common" />,
        content: getLabel(30986, '保存'),
        onClick: this.onSubmit,
      },
      {
        key: 'emailAutoClearLog',
        icon: <i className="icon-coms-common" />,
        content: getLabel(515459, '邮件清理日志'),
        onClick: this.showEmailClearLog,
      },
    ];
    setStoreState({ rightMenuDatas });
    autoClearRuleStore.getEmailAutoClearRuleCondition();

    if (!window.weaEmailEngine) {
      // 异步加载别模块的静态资源
      eventRegister.loadModule(
        'b_email',
        () => {
          // 加载成功
          // store 中更新load加载状态
          autoClearRuleStore.setLoaded(true);
        },
        () => {
          // console.log("加载失败");
          // 加载文件失败 的业务处理， 网络超时，没文件之类
        },
      );
    } else {
      autoClearRuleStore.setLoaded(true);
    }
  }

  componentWillUnmount() {
    const {
      settingStore: { autoClearRuleStore },
    } = this.props;
    autoClearRuleStore.clear();
  }

  getEditRef = (el) => {
    this.editrule = el;
  };

  getForm = (form, fields) => {
    const { isFormInit } = form;
    const { autoClear } = form.getFormParams();
    let group = [];
    isFormInit &&
      toJS(fields) &&
      toJS(fields).map((c) => {
        if (c.key === 'openSet') {
          let items = [];
          c.items.map((field) => {
            if (field.domkey[0] === 'autoClear') {
              let helptip = (
                <span style={{ paddingLeft: '10px' }}>
                  <WeaHelpfulTip
                    ecId={`${
                      (this && this.props && this.props.ecId) || ''
                    }_WeaHelpfulTip@t5jann@${field.domkey[0]}`}
                    title={getLabel(
                      515475,
                      '打开开关后，每天根据规则自动清理一次邮件',
                    )}
                    placement="right"
                  />
                </span>
              );
              items.push({
                com: RenderForm(
                  form,
                  field,
                  { style: { width: '100%' } },
                  helptip,
                ),
              });
            } else {
              items.push({ com: RenderForm(form, field) });
            }
          });
          group.push(
            <WeaSearchGroup
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaSearchGroup@vvy5za@${c.title}`}
              col={1}
              title={c.title}
              needTigger={true}
              showGroup={c.defaultshow}
              items={items}
            />,
          );
        } else if (c.key === 'conditionSet' && autoClear === '1') {
          let items = [];
          c.items.map((field) => {
            if (field.domkey[0] === 'autoClear') {
              let helptip = (
                <span style={{ paddingLeft: '10px' }}>
                  <WeaHelpfulTip
                    ecId={`${
                      (this && this.props && this.props.ecId) || ''
                    }_WeaHelpfulTip@t6ee8z@${field.domkey[0]}`}
                    title={getLabel(
                      515475,
                      '打开开关后，每天根据规则自动清理一次邮件',
                    )}
                    placement="right"
                  />
                </span>
              );
              items.push({
                com: RenderForm(
                  form,
                  field,
                  { style: { width: '100%' } },
                  helptip,
                ),
              });
            } else {
              items.push({ com: RenderForm(form, field) });
            }
          });
          group.push(
            <WeaSearchGroup
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaSearchGroup@g992su@${c.title}`}
              col={1}
              title={c.title}
              needTigger={true}
              showGroup={c.defaultshow}
              items={items}
            />,
          );
        }
      });
    return group;
  };

  /*
    columns.condition 配置
    newRuleCondition.subChildren = {
      ...newRuleCondition.subChildren,
      '1': {
        type: 'INPUT',
        viewAttr: 3,
        helpfulTip: '使用关键字搜索，即主题中包含该关键字即符合该条件。',
        helpfulTipProps: { placement: "right" }
      },
      '3': {
        type: 'INPUTNUMBER',
        label: '超过',
        viewAttr: 3,
        min: 7,
        tip: '天',
        helpfulTip: '填写天数不能小于7',
        helpfulTipProps: { placement: "right" }
      }
    }
  */
  renderTable = (ruleEntity) => {
    const {
      prefixCls,
      settingStore: { autoClearRuleStore },
    } = this.props;
    const { ruleConditionInfo } = autoClearRuleStore;
    const columns = [
      {
        title: (
          <div className={`${prefixCls}-rule-title`}>
            {`${getLabel(15364, '条件')}/${getLabel('579', '规则')}`}
            <WeaHelpfulTip
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaHelpfulTip@r02lp8@ruleCondition`}
              title={getLabel('515464', '取各条件规则的交集进行清理')}
              placement="right"
            />
          </div>
        ), // 列名
        dataIndex: 'ruleCondition', // 列的id 对应数据
        key: 'ruleCondition', // 前端渲染key值
        com: [
          {
            label: '',
            type: 'CASCADER',
            key: 'ruleCondition',
            compDef: toJS(ruleConditionInfo),
          },
        ],
        colSpan: 1,
      },
    ];

    return (
      <div className={`${prefixCls}-rule`}>
        <WeaTableEditable
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaTableEditable@xhpa6g`}
          className="edit-rule"
          ref={this.getEditRef}
          datas={toJS(ruleEntity)}
          showCopy={false}
          columns={columns}
          validator={{ rules: { ruleCondition: 'required' } }} // validator is invalid
          onChange={this.onEditChange}
        />
      </div>
    );
  };
  onEditChange = (v) => {
    const {
      settingStore: { autoClearRuleStore },
    } = this.props;
    autoClearRuleStore.setStoreState({ ruleEntity: v });
  };

  getBtnsMore = () => {
    let btnsMore = [
      {
        key: 'emailAutoClearLog',
        content: getLabel(515459, '邮件清理日志'),
        disabled: false,
        onClick: this.showEmailClearLog,
      },
    ];
    return btnsMore;
  };

  showEmailClearLog = () => {
    if (this.refs.autoclearref.clearLog) {
      this.refs.autoclearref.clearLog.wrappedInstance.openDialog('', () =>
        this.setState({ clearVisible: true }),
      );
    }
  };

  /* 提交 */
  onSubmit = () => {
    const {
      settingStore: { autoClearRuleStore },
    } = this.props;
    const {
      ruleEntity,
      operateUserEmailAutoClearRuleSetting,
    } = autoClearRuleStore;
    let flag = true;
    if (toJS(ruleEntity) && toJS(ruleEntity).length > 0) {
      toJS(ruleEntity).map((item) => {
        const requiredArr = ['1', '2', '3', '10'];
        if (item.ruleCondition) {
          if (
            requiredArr.includes(item.ruleCondition[0]) &&
            !item.ruleCondition[1]
          ) {
            message.error(getLabel('515611', '您有必填项未填，请检查！'));
            flag = false;
          }
        }
      });
      let replaceRule = toJS(ruleEntity).map((item) => {
        if (item.ruleCondition[1] && item.ruleCondition[1].replaceDatas) {
          let datas = item.ruleCondition[1].replaceDatas[0];
          if (datas && datas.children) {
            delete datas.children;
            delete datas.title;
          }
        }
        return item;
      });
      if (flag) {
        operateUserEmailAutoClearRuleSetting({
          ruleCondition: JSON.stringify(replaceRule),
        });
      }
    } else {
      operateUserEmailAutoClearRuleSetting({
        ruleCondition: JSON.stringify(toJS(ruleEntity)),
      });
    }
  };

  onCancelLog = () => this.setState({ clearVisible: false });

  render() {
    const {
      prefixCls,
      settingStore: { autoClearRuleStore },
    } = this.props;
    const {
      ruleEntity,
      autoClearRuleForm,
      autoClearRuleFields,
    } = autoClearRuleStore;
    const { autoClear } = autoClearRuleForm.getFormParams();
    const MailClearLogDialog = this.MailClearLogDialog;
    return (
      <div className={prefixCls}>
        <div className={`${prefixCls}-form`}>
          <WeaNewScroll
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaNewScroll@7nkm11`}
            style={{ maxHeight: 500 }}
          >
            {this.getForm(autoClearRuleForm, autoClearRuleFields)}
            {autoClear === '1' && this.renderTable(ruleEntity)}
            {autoClearRuleStore.loaded &&
              window.weaEmailEngine &&
              window.weaEmailEngine.components &&
              window.weaEmailEngine.components.MailClearLogDialog && (
                <MailClearLogDialog
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_undefined@g1v8d2`}
                  ref="autoclearref"
                  visible={this.state.clearVisible}
                  onCancel={this.onCancelLog}
                />
              )}
          </WeaNewScroll>
        </div>
        <div className={`${prefixCls}-operate`}>
          <Button
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_Button@hglplf`}
            type="primary"
            onClick={this.onSubmit}
          >
            {getLabel(30986, '保存')}
          </Button>
          <WeaMoreButton
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaMoreButton@9pjuox`}
            datas={this.getBtnsMore()}
          />
        </div>
      </div>
    );
  }
}

export default AutoClearRule;
